<?php

namespace app\common\service;
use think\Db;

class MarketService{

	public static function getMarket(){
		//刷新币种价格
		$coin = model('CoinModel')->getCoinList();
		$rmb  = C('huilv');
		foreach ($coin as $key => $val) {

			$name = strtolower($val['name']);
			$data = self::dataio('https://data.gateio.co/api2/1/ticker/'.$name.'_usdt');
			if($data){
				$data['rmb'] = round($rmb * $data['price'],4);
				model('CoinModel')->updateCoin($val['id'],$data);
				model('WalletModel')->updateWallet($val['wid'],['price'=>$data['price'],'rmb'=>$data['rmb']]);
			} else {
				$coin_rmb = round($rmb * $val['price'],4);
				if($coin_rmb != $val['rmb'])
				model('CoinModel')->updateCoin($val['id'],['rmb'=>$coin_rmb]);
				model('WalletModel')->updateWallet($val['wid'],['rmb'=>$coin_rmb]);
			}
		}

		$hangqing = model('CoinModel')->getHangqing();

		$coin_other = C('hangqing_coin');
		$coin_other = explode("," , $coin_other);
		foreach ($coin_other as $key => $val) {
			$name = strtolower($val);
			$data = self::dataio('https://data.gateio.co/api2/1/ticker/'.$val.'_usdt');
			if($data){
				$data['rmb'] = round($rmb * $data['price'],4);
				$data['name'] = strtoupper($val);
				$hangqing[] = $data;
			}
		}
		cache('hangqing',$hangqing);
		return $hangqing;
	}
		

	public static function dataio($url){
		$res = curl($url);
		$res = json_decode($res,1);
		$data = [];
		if(isset($res['result'])){
			$data['price'] = $res['last'];
			$data['vol']   = round($res['baseVolume'],4);
			$data['rate']  = round($res['percentChange'],2);
			return $data;
		} else {
			return false;
		}
	}

	/*
	获取汇率
	 */
	public static function getHuilv(){
		$data = curl('http://web.juhe.cn:8080/finance/exchange/rmbquot?type=&bank=&key=65a9172109bfec94a456576a3329f2f3');
		$data = json_decode($data,true);
		if($data['error_code']==0){
			$market = $data['result'][0];
			foreach ($market as $key => $val) {
				if($val['name']=='美元'){			
					$usd = round($val['bankConversionPri']/100,4);
					break;
				}
			}
		} else {
			$usd = 7;
		}
		$res = Db::table('tp_system_param')->where('param','huilv')->update(['val'=>$usd]);
		$sql = 'update tp_coin set rmb = price*'.$usd;
		Db::execute($sql);
		$sql = 'update tp_coin_wallet set rmb = price*'.$usd;
		Db::execute($sql);
		if($res){
			return true;
		} else{
			return false;
		}
	}
}